<?php

namespace App\Imports;

use App\Models\DriverModel;
use App\Models\OrderModel;
use App\Models\SupplierModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use stdClass;

class OrderWeightImport implements ToCollection, WithMultipleSheets
{


    const DIRVER = 1;
    const SUPPLIER = 2;
    const BOTH = 3;

    public static $c = 0;

    private $result;

    public function __construct() {
        $this->result = new stdClass;
    }

    public function collection(Collection $rows){
        $faild_rows = []; //失败的行数
        $oids = [];
        $data = [];
        foreach ($rows as $k => $row) {
            //履约单号	计费重
            //231321   2121
            if($k == 0) continue;

            $order_sn = $row[0] ?? '';
            $weight = $row[1] ?? 0;
            //跳过空白行
            if(empty($order_sn) && empty($weight)){
                continue;
            }

            if(empty($order_sn)) {
                $faild_rows[] = ['row' => $k, 'reason' => '未填写订单编号'];
                continue;
            }

            if($weight < 0) {
                $faild_rows[] = ['row' => $k, 'reason' => '计费重不能小于0'];
                continue;
            }

            $order = OrderModel::query()->where('sn', $order_sn)->first();
            if(!$order) {
                $faild_rows[] = ['row' => $k, 'reason' => '订单编号错误'];
                continue;
            }

            if(isset($oids[$order->id])) {
                $faild_rows[] = ['row' => $k, 'reason' => '单号和第'. $oids[$order->id]. '行重复'];
                continue;
            }

            $oids[$order->id] = $k;
            $data[] = [
                'id' => $order->id,
                'weight' => $weight
            ];
        }

        $this->result->faild_rows = $faild_rows;
        $this->result->data = $data;
    }

    public function sheets(): array {
        return [ 0 => $this];
    }

    public function get_result(){
        return $this->result;
    }


}
